<?php
JLoader::register("PCalendarHelper", OC_App::getAppPath('calendar') . "/lib/helper.php");
JLoader::register("PCalendarModelCalendar", OC_App::getAppPath('calendar') . "/lib/calendar.php");
JLoader::register("PCalendarModellistview", OC_App::getAppPath('calendar') . "/lib/listview.php");
JLoader::register("ResumeShare", OC_App::getAppPath('resumes') . "/lib/share/share.php");
JLoader::register("OC_Share_Backend_Calendar", OC_App::getAppPath('calendar') . "/lib/share/calendar.php");
JLoader::register("PCalendarModelObject", OC_App::getAppPath('calendar') . "/lib/object.php");

// Load other apps for file previews
OC_App::loadApps();

function handleError($errormsg){
   header('HTTP/1.0 404 Not Found');
   $tmpl = new OCP\Template('', '404', 'base');
   $tmpl->assign('error', $errormsg);
   $tmpl->printPage();
   exit;  
}

function handleEvent($token,$sharewith){
   $errormsg = '';
   $feedback = JRequest::getInt('feedback', 0);
   // Check token and email
   $shareEvent = PCalendarHelper::getShareEvent($token, $sharewith);

   if ( !$shareEvent ) {
      $errormsg = '没有找到相关的面试信息。请联系邀请您参加面试的用户，以确保该链接正确。';
      handleError($errormsg);
   } elseif ( empty($feedback) ) {
      if ( OC_User::isLoggedIn() ) {
         // For login user, redirect to calendar's home page
         OC_Response::redirect(OCP\Util::linkToRoute('calendar_home'));
         exit;
      }
      $userid = $shareEvent['userid'];
      $masteruser = ResumeShare::getCompanyIdFromOwner($shareEvent['uid_owner']);
      $app = PFactory::getApplication();
      $app->setUserState('calendarshare_companyid', $masteruser->id);

      // Create default calendar (if necessary)
      $calendar_model = new PCalendarModelCalendar();
      $object_model = new PCalendarModelObject();
      $calendars = $calendar_model->allCalendars($userid, false);
      if( count($calendars) == 0 ) {
         $calendar_model->addDefaultCalendars($userid);
         $calendars = $calendar_model->allCalendars($userid, true);
      }

      // Fix currentview for fullcalendar (if necessary)
      if(OCP\Config::getUserValue($userid, 'calendar', 'currentview', 'month') != "month") {
         OCP\Config::setUserValue($userid, "calendar", "currentview", "month");
      }
      $objects_number = $object_model->getObjectNumber($masteruser->id);
      $tmpl = new OCP\Template('calendar', 'calendar', 'user');

      //if(array_key_exists('showevent', $_GET)) {
      //   $tmpl->assign('showevent', $_GET['showevent']);
      //}      
      $tmpl->assign('objects_number',$objects_number);
      $tmpl->assign('shareEvent', $shareEvent);
      $tmpl->assign('calendarid', $calendars[0]['id']);
      $tmpl->assign('page_title', '面试管理');
      $tmpl->printPage();
   } else {
      $objectid = $shareEvent['objectid'];

      $masteruser = ResumeShare::getCompanyIdFromOwner($shareEvent['uid_owner']);
      $app = PFactory::getApplication();
      $app->setUserState('calendarshare_companyid', $masteruser->id);

      if(empty($masteruser)){
         $errormsg = '没有找到相关反馈页面的信息。请联系邀请您参加反馈的用户，以确保该链接正确。';
         handleError($errormsg);
      }

      $round = PCalendarHelper::getInterviewerEmailDataFromObjectid($objectid,$masteruser->id);
      $interviewer = PCalendarHelper::getInterviewerNameFromObjectid($objectid);
      $displayname = $interviewer == $sharewith ? "" : $interviewer;
      $model = new PCalendarModellistview();
      $feedbacknum = $model->getFeedbackNum($objectid);
      if(count($feedbacknum)>=1) {
         // put w not part of array to avoid email rawurlencode 
         OC_Response::redirect(OC_Helper::linkToRoute("calendar_interviewfeedback", array('id'=>$objectid)).'&w='.$sharewith);
         exit;
      }

      $questionlist = $model->getFeedbackQuestion();
      $suggestionlist = $model->getFeedbackSuggestion();


      $tmpl = new OCP\Template('calendar', 'calendar.interviewfeedback', 'user');

      $userid = $shareEvent['userid'];
      $objecttype = $round['eventtype'];
      if ( $objecttype == 'VEVENT' ) {
         // If share, get shared resume link
         $resume_link = PCalendarHelper::getResumeShareLink($round['jobseekerid'], $userid);
      }

      $absent = JRequest::getInt("absent", 0);
      $absent = $absent > 0 ? 1 : 0;
      $notattended = JRequest::getInt('notattended', 0);
      $notattended = $notattended > 0 ? 1 :0;

      $tmpl->assign('absent', $absent);
      $tmpl->assign('notattended', $notattended);
      $tmpl->assign('resume_link', $resume_link);
      $tmpl->assign('round', $round);
      $tmpl->assign('interviewer',$interviewer);
      $tmpl->assign('displayname', $displayname);
      $tmpl->assign('sharewith',$sharewith);
      $tmpl->assign('objectid', $objectid);
      $tmpl->assign('questionlist',$questionlist);
      $tmpl->assign('suggestionlist',$suggestionlist);
      $tmpl->assign('page_title', '面试反馈');
      $tmpl->printPage();
   }
}

function handleOffer($token,$sharewith){
   $errormsg = '';
   $offerstatus = JRequest::getString('o','');
   if(empty($offerstatus)){
      $errormsg ='没有找到相关的入职Offer信息。请联系给您发送Offer的用户，以确保该链接正确。';
      handleError($errormsg);
   }
   $shareOffer = PCalendarHelper::checkOfferToken($token,$sharewith);
   if(!$shareOffer){
      $errormsg ='没有找到相关的入职Offer信息。请联系给您发送Offer的用户，以确保该链接正确。';
      handleError($errormsg);
   }else{
      $object_model = new PCalendarModelObject();
      $userofferinfo = $object_model->getShareOfferData($token,$sharewith);
      $errormsg = '';
      if(empty($userofferinfo)){
         $errormsg = "没有找到相关信息。";           
      }else{
         if($offerstatus == 'accept'){
            if(!empty($userofferinfo['offer_stat']) && $userofferinfo['offer_stat'] == PCalendarHelper::OFFER_FEEDBACKSTATUS_ACCEPTED){
               $errormsg = '您已成功接受此Offer。';
            }elseif(!empty($userofferinfo['offer_stat']) && $userofferinfo['offer_stat'] == PCalendarHelper::OFFER_FEEDBACKSTATUS_REJECTED){
               $errormsg = '您已拒绝此offer，无法再接受，如有疑问，请联系'.$userofferinfo['company_name'].'的人事主管。';
            }else{
               $object_model->acceptoffer($userofferinfo,$errormsg);
               if(empty($errormsg)){
                   $tmpl = new OCP\Template('calendar', 'acceptoffer', 'base');  
                   $tmpl->assign('page_title', '接受入职Offer');  
                   $tmpl->assign('jobseekername',$userofferinfo['jobseekername']);
                   $tmpl->printPage();
               }
            }

         }elseif($offerstatus == 'reject'){
            if(!empty($userofferinfo['offer_stat']) && $userofferinfo['offer_stat'] == PCalendarHelper::OFFER_FEEDBACKSTATUS_REJECTED){
               $errormsg = '您已成功拒绝此Offer。';
            }elseif(!empty($userofferinfo['offer_stat']) && $userofferinfo['offer_stat'] == PCalendarHelper::OFFER_FEEDBACKSTATUS_ACCEPTED){
               $errormsg = '您已接受此offer，无法再拒绝，如有疑问，请联系'.$userofferinfo['company_name'].'的人事主管。';
            }else{
               $tmpl = new OCP\Template('calendar', 'rejectoffer', 'base');
               $tmpl->assign('page_title', '放弃入职Offer'); 
               $tmpl->assign('userofferinfo',$userofferinfo);
               $tmpl->printPage();
            }
         }
      }
      if(!empty($errormsg)){
         handleError($errormsg);
      }
      exit;
   }
}
$token = JRequest::getString('t', '');
$sharewith = JRequest::getString('w', '');
$service = JRequest::getString('service','');
if(!empty($token) && !empty($sharewith)){
   switch ($service) {
      case 'offer':
         handleOffer($token,$sharewith);
         break;
      case 'event':
         handleEvent($token,$sharewith);
   }

}elseif(!empty($sharewith)) {
   OC_Response::redirect(OC_Helper::linkToRoute('company_login'));
   exit;
}
else {
   $errormsg = '没有找到相关的面试信息。请联系邀请您参加面试的用户，以确保该链接正确。';
   handleError($errormsg);
}

